<?php
namespace Home\Controller;

/**
 * 担保交易 控制器
 */
class DuobaoController extends HomeController
{
	public function index()
	{
		if (!userid()) {
			redirect('/#login');
		}
		$this->transactionTotal();

		$SecuredTransactionModel = M('SecuredTransaction');
		$status = I('get.status');
		if($status >= 1){
			$this->assign('status',$status);
			$this->assign('count',$SecuredTransactionModel->where("(user_id=%d or other_side_username='%s') and status = %d",array(userid(),username(),$status))->count());
		}else {
			$this->assign('status',0);
			$this->assign('count',$SecuredTransactionModel->where("user_id=%d or other_side_username='%s'",array(userid(),username()))->count());
		}
		$this->display();
	}

	/**
	 * ajax 分页加载交易列表
	 */
	public function transactionList($page,$pageCount = 10) 
	{
		if (!userid()) {
			redirect('/#login');
		}
		$this->transactionTotal();
		$SecuredTransactionModel = M('SecuredTransaction');
		$status = I('get.status');
		$data = null;
		if($status >= 1){
			$data = $SecuredTransactionModel->where("(user_id=%d or other_side_username='%s') and status = %d",array(userid(),username(),$status))->page($page,$pageCount)->order('id desc')->select();
		}else {
			$data = $SecuredTransactionModel->where("user_id=%d or other_side_username='%s'",array(userid(),username()))->page($page,$pageCount)->order('id desc')->select();
		}
		$this->ajaxReturn($data);
	}

	/**
	 * 跳转到发布担保交易页面,
	 * 首先判断登录,查询中介费用比例,支持的交易货币类型(Coin 表),然后跳转
	 */
	public function add()
	{
		if (!userid()) {
			redirect('/#login');
		}
		$this->transactionTotal();
		$ConfigModel = M('Config');
		$this->assign('agency_fee_pay_percent',$ConfigModel->find(1)['agency_fee_pay_percent']);	
		$this->assign('coins',M('Coin')->where('status=1')->order('id desc')->select());
		$this->display();
	}

	/**
	 * 担保交易信息初步保存
	 * //TODO: 交易日志暂未存储
	 */
	public function save() {
		if (!userid()) {
			redirect('/#login');
		}
		$ConfigModel = M('Config');
		$agencyFeePayPercent = $ConfigModel->find(1)['agency_fee_pay_percent'];	

		$SecuredTransaction = M('SecuredTransaction');
		$data   =   I('post.');
		$data['status'] = 1;
		$data['create_time'] = date('Y-m-d H:i:s',time());
		$data['user_id'] = userid();
		$data['business_no'] = 'securedTransaction'.userid().time().strRand();
		//计算双方的支付总价格
			
		$total = $data['coin_price'] * $data['coin_count'];
		if($data['agency_fee_pay_type'] == 1){
			$data['coin_total'] = $total + $agencyFeePayPercent/100.0 * $total; 
			$data['other_coin_total'] = $total; 
		}else if($data['agency_fee_pay_type'] == 2){
			$data['other_coin_total'] = $total - $agencyFeePayPercent/100.0 * $total; 
			$data['coin_total'] = $total; 
		}else if($data['agency_fee_pay_type'] == 3){
			$data['other_coin_total'] = $total- $agencyFeePayPercent/200.0 * $total; 
			$data['coin_total'] = $total + $agencyFeePayPercent/200.0 * $total; 
		}else{
			$data['other_coin_total'] = $total - $agencyFeePayPercent/100.0 * $total; 
			$data['coin_total'] = $total + $agencyFeePayPercent/100.0 * $total; 
		}
		
		$result = $SecuredTransaction->add($data);
		$this->ajaxReturn($result);
	}

	/**
	 * 查看详细,在该页面进行交易接受/拒绝
	 */
	public function detail($id) {
		if (!userid()) {
			redirect('/#login');
		}
		$this->transactionTotal();
		$SecuredTransaction = M('SecuredTransaction');
		$data = $SecuredTransaction->find($id);
		//查询交易货币名
		$coinName = M("Coin")->find($data['coin_type'])['title'];
		debug($coinName);
		$data['coinName'] = $coinName;

		
		$this->assign("data",$data);
		$this->display();
	}

	/**
	 * 接受交易请求
	 */
	public function accept(){
		if (!userid()) {
			redirect('/#login');
		}
		$id = I('post.id');
		$SecuredTransaction = M('SecuredTransaction');
		$UserCoin = M('UserCoin');
		$data = $SecuredTransaction->find($id);
		
		$coin = M('Coin')->find($data['coin_type']);
		//积分
		$userId = $data['user_id'];
		$otherUserId = userid($data['other_side_username']);
		$userCoin = $UserCoin->where('userid = %d',$userId)->find();
		$otherUserCoin = $UserCoin->where('userid = %d',$otherUserId)->find();
		$userCoin[$coin['name']] = $userCoin[$coin['name']] - $data['coin_total'];
		$otherUserCoin[$coin['name']] = $otherUserCoin[$coin['name']] + $data['other_coin_total'];
		if($data['role'] == 1){//我是卖方,对方是买方
			if($userCoin[$coin['name']]>0){
				$data['status'] = 2;
				$data['finish_time'] =  date('Y-m-d H:i:s',time());
				$SecuredTransaction->save($data);
				$UserCoin->save($userCoin);
				$UserCoin->save($otherUserCoin);
				$this->ajaxReturn(array('result'=>true,'msg'=>'支付成功'));
			}else {
				$this->ajaxReturn(array('result'=>false,'msg'=>'支付失败,余额不足'));
			}
		}else {//我是买方,对方是卖方
			if($otherUserCoin[$coin['name']]>0){
				$data['status'] = 2;
				$data['finish_time'] =  date('Y-m-d H:i:s',time());
				$SecuredTransaction->save($data);
				$UserCoin->save($userCoin);
				$UserCoin->save($otherUserCoin);
				$this->ajaxReturn(array('result'=>true,'msg'=>'支付成功'));
			}else {
				$this->ajaxReturn(array('result'=>false,'msg'=>'支付失败,余额不足'));
			}
		}
	}

	/**
	 * 拒绝交易
	 */
	public function refuse(){
		if (!userid()) {
			redirect('/#login');
		}
		$id = I('post.id');
		$SecuredTransaction = M('SecuredTransaction');
		$data = $SecuredTransaction->find($id);
		$data['status'] = 3;
		$data['finish_time'] =  date('Y-m-d H:i:s',time());
		$SecuredTransaction->save($data);
		$this->ajaxReturn(true);
	}
  
	/**
	 * 交易额查询
	 */
	private function transactionTotal(){
		$transactions1 = M('SecuredTransaction')->where("user_id=%d or other_side_username = '%s'",userid(),username())->select();
		$total1 = 0;
		foreach ($transactions1 as $item){ 
			if($item['user_id'] == userid()){
				if($item['role'] == 1){
					$total1 = $total1 - $item["coin_total"];
				}else {
					$total1 += $item["other_coin_total"];
				}
			}else {
				if($item['role'] == 1){
					$total1 += $item["other_coin_total"];
				}else {
					$total1 = $total1 - $item["coin_total"];
				}
			}
		  } 
		//交易中
		$transactions2 = M('SecuredTransaction')->where("(user_id=%d or other_side_username = '%s' )and status = 1",userid(),username())->select();
		$total2 = 0;
		foreach ($transactions2 as $item){ 
			if($item['user_id'] == userid()){
				if($item['role'] == 1){
					$total2 = $total2 - $item["coin_total"];
				}else {
					$total2 += $item["other_coin_total"];
				}
			}else {
				if($item['role'] == 1){
					$total2 += $item["other_coin_total"];
				}else {
					$total2 = $total2 - $item["coin_total"];
				}
			}
		  } 
		//以结束(已经完成的)
		$transactions3 = M('SecuredTransaction')->where("(user_id=%d or other_side_username = '%s' )and status = 2",userid(),username())->select();
		$total3 = 0;
		foreach ($transactions3 as $item){ 

			if($item['user_id'] == userid()){
				if($item['role'] == 1){
					$total3 = $total3 - $item["coin_total"];
				}else {
					$total3 += $item["other_coin_total"];
				}
			}else{
				if($item['role'] == 1){
					$total3 += $item["other_coin_total"];
				}else {
					$total3 = $total3 - $item["coin_total"];
				}
			}
		  } 
		$this->assign('total1',$total1);
		$this->assign('total2',$total2);
		$this->assign('total3',$total3);
	}
}

